package com.morgan.basemodule.activity

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.os.SystemClock
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.atomic.AtomicLong

/**
 *description：
 *<br>author：caowugao
 *<br>time：2021/4/2 0002 17:24
 */
class ActManager private constructor(){

    private var lastJumpPathName : String? = null
    private val lastJumActTimeUs : AtomicLong by lazy { AtomicLong(0L) }

    private val actStack : Stack<Activity> by lazy { Stack<Activity>() }

    class Holder private constructor(){
        companion object {
            val INSTANCE = ActManager()
        }
    }

    companion object {
        fun getInstance() = Holder.INSTANCE
    }

    fun init(app : Application) {
        app.registerActivityLifecycleCallbacks(object :Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                actStack.push(activity)
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                try {
                    actStack.remove(activity)
                } catch (e : Throwable) {
                    e.printStackTrace()
                }
            }

        })
    }

    fun getCurrActivity() : Activity? = try {
        actStack.peek()
    } catch (e : Throwable) {
        e.printStackTrace()
        null
    }

    fun finishAllActivity() {
        if (actStack.isEmpty()) {
            return
        }

        do {
            try {
                actStack.pop().finish()
            } catch (e : Throwable) {
                e.printStackTrace()
            }
        } while (!actStack.isEmpty())
    }

    fun jump(path : String, durationUs: Long = 0L) {
        val now = SystemClock.uptimeMillis()
        if (!TextUtils.equals(lastJumpPathName, path)) {
            lastJumActTimeUs.getAndSet(now)
            lastJumpPathName = path
            ARouter.getInstance().build(path).navigation()
            return
        }
        if (now - lastJumActTimeUs.get() < durationUs) {
            return
        }
        lastJumActTimeUs.getAndSet(now)
        lastJumpPathName = path
        ARouter.getInstance().build(path).navigation()
    }

}